#include "atom.h"
#define ATOM_NONE_STANDARDIO
#include "drv_i2c.h"
#undef OK
#include <mraa/i2c.h>
#include "debug.h"
#include "syslog.h"

static size_t i2c_bit_xfer(I2c* bus, struct i2c_msg msgs[], uint32_t num)
{
    struct i2c_msg* msg;
    UpboardI2c * i2c = (UpboardI2c * )bus;
    int ret = 0;
    mraa_result_t result;

    mraa_i2c_context wire = (mraa_i2c_context)i2c->Protected.wire;
    
    for (int i = 0; i < num; i++)
    {
        int cnt = 0;
        msg = &msgs[i];

        if (msg->flags & I2C_RD)
        {
            result = mraa_i2c_read(wire, msg->buf, msg->len);
            if(result != MRAA_SUCCESS ){
                return ret;
            }else{
                ret++;
            }
        }
        else
        {
            if( !(msg->flags & I2C_NO_START) ){
                result = mraa_i2c_address(wire, msg->addr);
                if (result != MRAA_SUCCESS) {
                    return ret;
                }
            }

            result = mraa_i2c_write(wire, msg->buf, msg->len);
            if (result != MRAA_SUCCESS) {
                return ret;
            }
            else {
                ret++;
            }
        }
    }

    return ret;
}

static I2cOps _ops = {
    i2c_bit_xfer,
    NULL
};

static UpboardI2c _i2c;

void UpboardI2cCreate()
{
    _i2c.super.Protected.ops = &_ops;
    _i2c.Protected.wire = (POINTER)mraa_i2c_init(1); // Assuming I2C bus 1
    I2cCreate(&_i2c.super, "i2c1");
    SYSLOG(LOG_INFO, "i2c module initialized");
}
